#pragma once

#include <iostream>
#include <memory>
#include "Socket.hpp"
#include "Connection.hpp"


// 该类未来统一进行listensock的管理工作，获取新链接

using namespace socket_ns;

class Listener
{
public:
    Listener(uint16_t port) : _port(port), _listensock(std::make_unique<TcpSocket>())
    {
        _listensock->BuildListenSocket(_port);
    }
    int ListenSockfd()
    {
        return _listensock->Sockfd();
    }
    void Accepter(Connection *conn)
    {
        // LOG(DEBUG,"%d sockfd ready\n",conn->Sockfd());
        while (true)
        {
            errno = 0;
            InetAddr addr;
            int code = 0;
            int sockfd = _listensock->Accepter(&addr, &code);
            if (sockfd > 0)
            {
                // 该sockfd获取成功了，我们该怎么办？
                LOG(INFO,"获取链接成功，客户端: %s:%d, sockfd: %d\n",addr.Ip().c_str(),addr.Port(),sockfd);
                conn->_R->AddConnection(sockfd,EPOLLIN|EPOLLET,addr,NormalConnection);
            }
            else
            {
                if(code == EWOULDBLOCK)
                {
                    LOG(INFO,"底层链接全部获取完毕\n");
                    break;
                }
                else if(code == EINTR)
                {
                    continue;
                }
                else
                {
                    LOG(ERROR,"获取链接失败！\n");
                    break;
                }
            }
        }
    }
    ~Listener()
    {
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensock;
};